package com.sanpu.kxe.business.main.presenter;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.gamerole.orcameralib.CameraActivity;
import com.sanpu.kxe.R;
import com.sanpu.kxe.base.ICommonProvider;
import com.sanpu.kxe.business.main.contract.CertificateHelpContract;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.common.interfaces.DialogViewListener;
import com.sanpu.kxe.jump.eventbus.ReviewPhotoEvent;
import com.sanpu.kxe.utils.DialogUtil;
import com.sanpu.kxe.utils.IntentTool;
import com.sanpu.kxe.utils.PublicProviderUtil;
import com.sanpu.kxe.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

/**
 * Description：认证照片示例Presenter
 * Created by 薛勇军 on 2018/7/20.
 */

public class CertificateHelpPresenter implements CertificateHelpContract.Presenter {

    private CertificateHelpContract.View mView;

    /**
     * 当前类型
     */
    private String currentType;

    private String cameraDir, cameraPath, cameraOcrPath;

    public CertificateHelpPresenter(CertificateHelpContract.View mView, String currentType) {
        this.mView = mView;
        this.currentType = currentType;
        String cameraName = "a" + System.currentTimeMillis();
        cameraDir = CommonConfig.DIR_APP_CACHE + "/";
        cameraPath = cameraDir + cameraName + ".jpg";
        cameraOcrPath = cameraDir + cameraName + ".jpg";
    }

    @Override
    public void checkPermission() {
        if (ContextCompat.checkSelfPermission(mView.getContext(), Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) mView.getContext(),
                    Manifest.permission.CAMERA)) {
                DialogUtil.getInstance().dialogExistTitleTwoBtnHaveCallBack(mView.getContext(),
                        mView.getContext().getResources().getString(R.string.permission_title),
                        "在设置中开启拍照权限，以保证应用拍照功能正常使用",
                        mView.getContext().getResources().getString(R.string.cancel),
                        mView.getContext().getResources().getString(R.string.permission_setting),
                        new DialogViewListener() {
                            @Override
                            public void btnRightConfirm() {
                                openSystemSetting();
                            }

                            @Override
                            public void btnLeftCancel() {

                            }
                        });
            } else {
                ActivityCompat.requestPermissions((Activity) mView.getContext(),
                        new String[]{Manifest.permission.CAMERA},
                        CommonConfig.REQUESTCODE_CERTIFICATE_HELP);
            }
        } else {
            onPhotographClick(mView.getContext());
        }
    }

    /**
     * 拍照
     */
    private void onPhotographClick(Context mContext) {
        File file = new File(cameraDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        if (TextUtils.equals(CommonConfig.TYPE_IDFROPIC, currentType)) {
            Intent intent = new Intent(mContext, CameraActivity.class);
            intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, cameraOcrPath);
            intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
            IntentTool.startActivityForResult(mContext, intent, CommonConfig.REQUESTCODE_CERTIFICATE_PICKER);
        } else if (TextUtils.equals(CommonConfig.TYPE_IDCONPIC, currentType)) {
            Intent intent = new Intent(mContext, CameraActivity.class);
            intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, cameraOcrPath);
            intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_BACK);
            IntentTool.startActivityForResult(mContext, intent, CommonConfig.REQUESTCODE_CERTIFICATE_PICKER);
        } else if (TextUtils.equals(CommonConfig.TYPE_IDHANDPIC, currentType)) {
            Intent intent = new Intent(mContext, CameraActivity.class);
            intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, cameraOcrPath);
            intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_GENERAL);
            IntentTool.startActivityForResult(mContext, intent, CommonConfig.REQUESTCODE_CERTIFICATE_PICKER);
        } else {
            PackageManager packageManager = mContext.getPackageManager();
            if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File f = new File(cameraPath);
                Uri uri;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    uri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileProvider", f);
                } else {
                    uri = Uri.fromFile(f);
                }
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                IntentTool.startActivityForResult(mContext, intent, CommonConfig.REQUESTCODE_CERTIFICATE_PICKER);
            } else {
                ToastUtil.showTextViewPrompt("当前设备不支持给此应用提供拍照功能，请检查系统权限");
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode) {
        if (requestCode == CommonConfig.REQUESTCODE_CERTIFICATE_PICKER) {
            File file = new File(cameraOcrPath);
            if (file.exists()) {
                EventBus.getDefault().post(new ReviewPhotoEvent(file.getPath(), currentType));
                IntentTool.finishActivity(mView.getContext());
            }
        }
    }

    /**
     * 打开系统设置
     */
    private void openSystemSetting() {
        ICommonProvider commonProvider = PublicProviderUtil.getProvider(ICommonProvider.class);
        if (commonProvider != null) {
            commonProvider.openSystemSetting((Activity) mView.getContext());
        }
    }

    @Override
    public void onDestroyPresenter() {
        if (mView != null) {
            mView = null;
        }
    }
}
